﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Baosight.ZNH.ZMCommon;
using Baosight.Platform.Core;
using Baosight.Platform.Core.ServiceModel;
using Baosight.Platform.Core.UI.Controls;
using Telerik.Windows.Controls;
using Baosight.ZNH.ZMCM.UI.Utils;
using Baosight.ZNH.ZMCommon.ChildWindows;
using Baosight.ZNH.ZMCM.UI.ChildWindows;
using System.Windows.Browser;


namespace Baosight.ZNH.ZMCM.UI
{
    public partial class ZMCMB0 : EFViewCmes
    {
        private StorageBlock block = new StorageBlock();
        string fdKeyId = "";

        public ZMCMB0()
        {
            InitializeComponent();
        }

        public override void Initialize(EIInfo initData)
        {
            initData.AddBlock(block.GetImportTypeBlock(true));
            base.Initialize(initData);
            base.BeforeAction += OnBeforeAction;
        }

        /// <summary>
        /// 列表中修改、删除前设置属性、参数
        /// 传递到后台代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnBeforeAction(object sender, EventArgs e)
        {
            EFViewCmesProperty _view = new EFViewCmesProperty();
            _view.EFGridCheckedRows = this.grid.GetCheckedEIRows();
            base.ViewProperty = _view;
        }

        /// <summary>
        /// 点击主表记录显示相应从表记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grid_SelectionChanged(object sender, Telerik.Windows.Controls.SelectionChangeEventArgs e)
        {
            if (null != this.grid.SelectedItem)
            {
                var fdKeyId = this.grid.SelectedItem.GetType().GetProperty("fdKeyId").GetValue(this.grid.SelectedItem, null);
                Dictionary<string, string> args = new Dictionary<string, string>();
                args.Add("fdImportmaterialId", fdKeyId.ToString());
                this.container.LoadView("ZMCMB1", args);
            }
            else
            {
                this.container.Content = null;
            }
        }

        /// <summary>
        /// 点击入库按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnRkButtonClick(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            button.IsEnabled = false;
            TempButton = button;

            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCMB2");
            eiInfo.Set("method", "queryNoteCode");

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, OnDoWorkCompletedQueryNote);
        }

        private void OnDoWorkCompletedQueryNote(object sender, DoWorkCompletedEventArgs e)
        {
            EIInfo inInfo = e.EIInfo;
            if (inInfo.Status == -1)
            {
                this.TempButtonOpen(true);
                this.OnCommitMessagePopup(inInfo);//操作失败，消息提醒
            }
            else
            {
                OpenImportPopup(inInfo, "物资入库管理-入库", "insert", null);
            }
        }

        /// <summary>
        /// 点击"红冲估收入库"按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnHcgsrkButtonClick(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            button.IsEnabled = false;
            TempButton = button;

            int count = this.grid.GetCheckedEIRows().Count;
            if (count <= 0)
            {
                this.OpenEFWindowAlert("请选择一条记录进行红冲估收入库！", true);
                return;
            }
            else if (count > 1)
            {
                this.OpenEFWindowAlert("最多只能选择一条记录进行红冲估收入库！", true);
                return;
            }
            else
            {
                List<EIRow> rows = this.grid.GetCheckedEIRows();
                string keyIds = "";
                foreach(EIRow grid_row in rows)
                {
                    if (!"估收入库".Equals(grid_row["fdImportType"].ToString()))
                    {
                        base.OpenEFWindowAlert("入库类型不是估收入库，不允许进行估收入库操作！", true);
                        return;
                    }
                    else if (grid_row["fdStatus"] != null)
                    {
                        if ("全部".Equals(grid_row["fdStatus"].ToString()))
                        {
                            base.OpenEFWindowAlert("选择的估收入库单[" + grid_row["fdNoteCode"].ToString() + "]已全部冲估完毕，不允许再次进行估收入库操作！", true);
                            return;
                        }
                    }
                    else
                    {
                        keyIds += grid_row["fdKeyId"].ToString() + ";";
                    }
                }

                EIInfo inInfo = new EIInfo();
                inInfo.Attributes.Add(EIConstants.ServiceNameKey, "ZMCMB3");
                inInfo.Attributes.Add(EIConstants.MethodNameKey, "query");

                EIBlock block = new EIBlock("inqu_status");
                EIColumn column = new EIColumn();
                column.SetName("fdImportmaterialId");
                block.AddColumn(column);
                EIRow row = new EIRow();
                row.Add("fdImportmaterialId", keyIds);
                block.AddRow(row);
                inInfo.AddBlock(block);

                HttpServiceAgent agent = new HttpServiceAgent();
                agent.CallService(inInfo, doWorkCompleted);
            }
        }

        /// <summary>
        /// 点击"红冲入库"按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnHcrkButtonClick(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            button.IsEnabled = false;
            TempButton = button;

            int count = this.grid.GetCheckedEIRows().Count;
            if (count <= 0)
            {
                this.OpenEFWindowAlert("请选择一条记录进行红冲入库！", true);
                return;
            }
            else if (count > 1)
            {
                this.OpenEFWindowAlert("最多只能选择一条记录进行红冲入库！", true);
                return;
            }
            else
            {
                if ("红冲".Equals(this.grid.GetCheckedEIRows()[0]["fdImportType"].ToString()))
                {
                    base.OpenEFWindowAlert("入库类型为红冲，不允许进行红冲操作！", true);
                    return;
                }
                else
                {
                    DialogParameters param = this.ModelDialogParameters("Confirm", "确定红冲入库所选择的记录？");
                    param.Closed = OnHcrkConfirmClosed;
                    EFWindow.Confirm(param);
                }
            }
            
        }

        /// <summary>
        /// 点击红冲入库确认按钮执行事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnHcrkConfirmClosed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == null || !e.DialogResult.Value)
            {
                this.TempButtonOpen(true);
                return;
            }

            if (e.DialogResult.Value)
            {
                //DataRange 的四个属性 All、CheckedItems、DirtyItems、None
                //ALL是当前页面所有的数据 CheckedItems是把EFGrid中check的数据 DirtyItems是把当前页面有改变的数据 None不提交
                base.Submit(OperationMode.Insert, "ZMCMB0", "insert", DataRange.CheckedItems, DoOperationCompleted);
            }
        }

        /// <summary>
        /// 点击红冲估收入库确认按钮执行事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnHcgsrkConfirmClosed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == null || !e.DialogResult.Value)
            {
                this.TempButtonOpen(true);
                return;
            }

            if (e.DialogResult.Value)
            {
                //DataRange 的四个属性 All、CheckedItems、DirtyItems、None
                //ALL是当前页面所有的数据 CheckedItems是把EFGrid中check的数据 DirtyItems是把当前页面有改变的数据 None不提交
                base.Submit(OperationMode.Insert, "ZMCMB0", "minusEvaluation", DataRange.CheckedItems, DoOperationCompleted);
            }
        }

        private void DoOperationCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            EIInfo inInfo = e.EIInfo;
            if (inInfo.Status == -1)
            {
                string _msg;
                if (inInfo.GetMsg() == null || inInfo.GetMsg() == "")
                {
                    _msg = "操作失败！";
                }
                else
                {
                    _msg = inInfo.GetMsg();
                }

                this.OpenEFWindowAlert(_msg, true);//列表中删除，操作失败后按钮生效
                return;
            }
            else
            {
                base.UpdateData(e.EIInfo);
                this.TempButtonOpen(true);//列表中删除，操作成功后按钮生效

                this.UpdateHomePageData(e.EIInfo);
                this.AfterMethod(e.EIInfo);
            }
        }

        private void doWorkCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            EIInfo inInfo = e.EIInfo;
            if (inInfo.Status == -1)
            {
                string _msg;
                if (inInfo.GetMsg() == null || inInfo.GetMsg() == "")
                {
                    _msg = "操作失败！";
                }
                else
                {
                    _msg = inInfo.GetMsg();
                }

                this.OpenEFWindowAlert(_msg, true);//列表中删除，操作失败后按钮生效
                return;
            }
            else
            {
                List<EIRow> rows = this.grid.GetCheckedEIRows();
                string keyIds = "";
                foreach (EIRow grid_row in rows)
                {
                    keyIds += grid_row["fdKeyId"].ToString() + ";";
                }

                OpenMinusEvaluatePopup(e.EIInfo, "物资红冲估收入库管理-冲估", "insert", keyIds);
            }
        }

        /// <summary>
        /// 弹出窗口关闭时执行的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmesWindow_Closed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == true)
            {
                this.grid.Refresh();//刷新Grid区域
                this.UpdateHomePageData(new EIInfo());//发布数据
            }

            //按钮生效
            base.TempButtonOpen(true);

            //超链接生效
            if (base.TempHyperlink != null)
            {
                base.TempHyperlink.IsEnabled = true;
                base.TempHyperlink = null;
            }
        }

        /// <summary>
        /// 构造入库页面内容、弹出页面
        /// </summary>
        /// <param name="eIInfo"></param>
        /// <param name="title"></param>
        private void OpenImportPopup(EIInfo _eIInfo, string _title, string _dialogType, string _args)
        {
            ImportMaterialInsert importMaterial = new ImportMaterialInsert(_dialogType);//构造一个新的修改页面
            importMaterial.EIDataContext = new Platform.Core.UI.EIDataContext();

            string noteCode = _eIInfo.Get("fdNoteCode").ToString();
            _eIInfo.AddBlock(this.EIDataContext.GetBlock("cmes.cs.units"));
            _eIInfo.AddBlock(block.GetImportTypeBlock(false));
            _eIInfo.AddBlock(block.GetMaterialSourceBlock(false));
            if ("insert".Equals(_dialogType))
            {
                importMaterial.fdNoteDate.Value = DateTime.Now.ToString("yyyy-MM-dd");
                importMaterial.fdDepotName.Value = this.EIDataContext.GetAttribute("depotName");
                importMaterial.fdNoteCode.Value = noteCode;
                (importMaterial.fdConfirmPeople.Content as CmesCustomView).Value = this.EIDataContext.GetAttribute("userId");
                (importMaterial.fdConfirmPeople.Content as CmesCustomView).Display = this.EIDataContext.GetAttribute("userName");
            }
            importMaterial.EIDataContext.Update(_eIInfo);

            CmesWindows _popup = new CmesWindows();//构造一个弹出页面
            _popup.WindowStartupLocation = Telerik.Windows.Controls.WindowStartupLocation.CenterOwner;
            _popup.TopOffset = -150;
            _popup.LeftOffset = -80;
            _popup.ResizeMode = ResizeMode.NoResize;//设置不能修改窗口大小
            _popup.Header = _title == null ? "" : _title;//设置Title
            _popup.Content = importMaterial;//让新增页面在弹出窗口显示
            _popup.Closed += new EventHandler<WindowClosedEventArgs>(CmesWindow_Closed);
            
            _popup.ShowDialog();//模态显示弹出窗口
        }

        /// <summary>
        /// 构造红冲估收入库页面内容、弹出页面
        /// </summary>
        /// <param name="eIInfo"></param>
        /// <param name="title"></param>
        private void OpenMinusEvaluatePopup(EIInfo _eIInfo, string _title, string _dialogType, string _args)
        {
            ImportMaterialHCGSInsert importMaterialHcgs = new ImportMaterialHCGSInsert();//构造一个新的修改页面
            importMaterialHcgs.EIDataContext = new Platform.Core.UI.EIDataContext();

            _eIInfo.AddBlock(this.EIDataContext.GetBlock("cmes.cs.units"));
            _eIInfo.AddBlock(block.GetImportTypeBlock(false));
            _eIInfo.AddBlock(block.GetMaterialSourceBlock(false));

            importMaterialHcgs.fdDepotName.Value = this.grid.GetCheckedEIRows()[0]["fdDepotName"].ToString();
            importMaterialHcgs.fdDepotCode.Value = this.grid.GetCheckedEIRows()[0]["fdDepotCode"].ToString();
            importMaterialHcgs.fdNoteCode.Value = _eIInfo.Get("fdNoteCode").ToString();
            importMaterialHcgs.fdOldKeyId.Value = _args;
            importMaterialHcgs.fdNoteDate.Value = DateTime.Now.ToString("yyyy-MM-dd");

            importMaterialHcgs.EIDataContext.Update(_eIInfo);

            CmesWindows _popup = new CmesWindows();//构造一个弹出页面
            _popup.ResizeMode = ResizeMode.NoResize;//设置不能修改窗口大小
            _popup.Header = _title == null ? "" : _title;//设置Title
            _popup.Content = importMaterialHcgs;//让新增页面在弹出窗口显示
            _popup.Closed += new EventHandler<WindowClosedEventArgs>(CmesWindow_Closed);

            _popup.ShowDialog();//模态显示弹出窗口
        }

        /// <summary>
        /// 重新基类的方法，当有新的EIInfo 数据发布时回调的方法
        /// 生产进度新增修改后更新统计数据
        /// </summary>
        /// <param name="data"></param>
        public override void OnEIDataPublished(EIInfo data)
        {
            //刷新 “得分”
            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCMB0");
            eiInfo.Set("method", "query");

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, UpdateStatisticsData);
        }

        /// <summary>
        /// 更新统计数据
        /// </summary>
        private void UpdateStatisticsData(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.GetStatus() != -1)
            {
                this.grid.UpdateData(e.EIInfo);
                this.grid.Refresh();
            }
        }

        public void OnPrintGSButtonClick(object sender, RoutedEventArgs e)
        {
            //按钮失效
            Button _button = sender as Button;
            _button.IsEnabled = false;
            base.TempButton = _button;
            int count = this.grid.GetCheckedEIRows().Count;
            if (count <= 0)
            {
                this.OpenEFWindowAlert("请选择一条记录进行打印！", true);
                return;
            }
            else if (count != 1)
            {
                this.OpenEFWindowAlert("只能选择一条记录进行打印！", true);
                return;
            }
            else
            {
                if (!this.grid.GetCheckedEIRows()[0]["fdImportType"].ToString().Equals("估收入库"))
                {
                    this.OpenEFWindowAlert("只能打印估收入库的记录！", true);
                    return;
                }
            }

            Dictionary<string, object> args = new Dictionary<string, object>();
            args.Add("fdImportmaterialId", this.grid.GetCheckedEIRows()[0]["fdKeyId"]);//传递隐患日报主键
            fdKeyId = "'" + this.grid.GetCheckedEIRows()[0]["fdKeyId"].ToString() + "'";
            HttpServiceAgent agent = new HttpServiceAgent();
            EIInfo eiInfo = new EIInfo();
            eiInfo.SetAttributes(args);
            eiInfo.Attributes.Add(EIConstants.ServiceNameKey, "ZMCMB1");
            eiInfo.Attributes.Add(EIConstants.MethodNameKey, "query");
            agent.CallService(eiInfo, OnPerviewQueryWorkCompleted);
        }

        private void OnPerviewQueryWorkCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status != -1)
            {
                if (e.EIInfo.GetBlock("result").GetRowCount() == 1)
                {
                    Uri uri = Uploader.ConstructAbsoluteUri("../admin/RunmaxReport.jsp?projectName=CMESReport&reportName=ZGReport&KeyId=" + fdKeyId);
                    HtmlPage.Window.Navigate(uri, "_blank");
                }
                else
                {
                    Uri uri = Uploader.ConstructAbsoluteUri("../admin/RunmaxReport.jsp?projectName=CMESReport&reportName=ZGDataReport&KeyId=" + fdKeyId);
                    HtmlPage.Window.Navigate(uri, "_blank");
                }
                
                //按钮生效
                base.TempButtonOpen(true);
            }
            else
            {
                EFWindow.Alert(e.EIInfo.GetMsg());
            }
        }

        public void OnPrintYBButtonClick(object sender, RoutedEventArgs e)
        {
            //按钮失效
            Button _button = sender as Button;
            _button.IsEnabled = false;
            base.TempButton = _button;
            int count = this.grid.GetCheckedEIRows().Count;
            if (count <= 0)
            {
                this.OpenEFWindowAlert("请选择一条记录进行打印！", true);
                return;
            }
            else if (count != 1)
            {
                this.OpenEFWindowAlert("只能选择一条记录进行打印！", true);
                return;
            }
            else
            {
                if (!this.grid.GetCheckedEIRows()[0]["fdImportType"].ToString().Equals("一般入库"))
                {
                    this.OpenEFWindowAlert("只能打印一般入库的记录！", true);
                    return;
                }
            }

            Dictionary<string, object> args = new Dictionary<string, object>();
            args.Add("fdImportmaterialId", this.grid.GetCheckedEIRows()[0]["fdKeyId"]);//传递隐患日报主键
            fdKeyId = "'" + this.grid.GetCheckedEIRows()[0]["fdKeyId"].ToString() + "'";
            HttpServiceAgent agent = new HttpServiceAgent();
            EIInfo eiInfo = new EIInfo();
            eiInfo.SetAttributes(args);
            eiInfo.Attributes.Add(EIConstants.ServiceNameKey, "ZMCMB1");
            eiInfo.Attributes.Add(EIConstants.MethodNameKey, "query");
            agent.CallService(eiInfo, OnPerviewYBQueryWorkCompleted);
        }

        private void OnPerviewYBQueryWorkCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status != -1)
            {
                if (e.EIInfo.GetBlock("result").GetRowCount() == 1)
                {
                    Uri uri = Uploader.ConstructAbsoluteUri("../admin/RunmaxReport.jsp?projectName=CMESReport&reportName=yanshou&KeyId=" + fdKeyId);
                    HtmlPage.Window.Navigate(uri, "_blank");
                }
                else
                {
                    Uri uri = Uploader.ConstructAbsoluteUri("../admin/RunmaxReport.jsp?projectName=CMESReport&reportName=YSDataReport&KeyId=" + fdKeyId);
                    HtmlPage.Window.Navigate(uri, "_blank");
                }

                //按钮生效
                base.TempButtonOpen(true);
            }
            else
            {
                EFWindow.Alert(e.EIInfo.GetMsg());
            }
        }
    }
}
